//
//  MovieLibraryViewController.m
//  觅影
//
//  Created by  陶虹 on 16/4/7.
//  Copyright © 2016年  陶虹. All rights reserved.
//

#import "MovieLibraryViewController.h"
#import "ClassifyCollectionViewCell.h"
#import "PopSoonCollectionViewCell.h"
#import "MovieLibraryMainModel.h"
#import "HotModel.h"
#import "SoonModel.h"
#import "LibraryDetailViewController.h"
#import "FiltrateViewController.h"
@interface MovieLibraryViewController ()<UICollectionViewDelegate,UICollectionViewDataSource, UICollectionViewDelegateFlowLayout,UIScrollViewDelegate>
@property (weak, nonatomic) IBOutlet UIScrollView *scrollView;
@property (weak, nonatomic) IBOutlet UICollectionView *classifyCollectionView;
@property (nonatomic, assign) CGFloat classItemWidth;
@property (nonatomic, strong) NSMutableArray *classifyArray;
@property (weak, nonatomic) IBOutlet UISegmentedControl *segmentController;
@property (weak, nonatomic) IBOutlet UICollectionView *popSoonCollectionView;
@property (nonatomic, assign) CGFloat popItemWidth;
@property (nonatomic, strong) NSMutableArray *popSoonArray;
@property (nonatomic, assign) NSInteger hotTotalCount;
@property (nonatomic, assign) NSInteger soonTotalCount;
@property (nonatomic, assign) NSInteger playingPage;
@property (nonatomic, assign) NSInteger soonPage;


@end

@implementation MovieLibraryViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    // 当scrollview遇到导航栏视图时 需要设置此属性为NO
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.navigationItem.title = @"影库";
    self.navigationController.navigationBar.translucent = NO;

    [self.segmentController addTarget:self action:@selector(segmentAction:) forControlEvents:UIControlEventValueChanged];
    self.scrollView.contentOffset = CGPointMake(KWIDTH, 0);
    self.scrollView.tag = 1000;
    self.scrollView.delegate = self;
    // 修改classifyCollection的layout值
    UICollectionViewFlowLayout *classLayout = (UICollectionViewFlowLayout *)self.classifyCollectionView.collectionViewLayout; // 强转以匹配类型
    // 设置间距为3 一行放两个collectionView
    self.classItemWidth = (KWIDTH - 3) / 2;
    // 设置item
    classLayout.itemSize = CGSizeMake(self.classItemWidth, self.classItemWidth);
    classLayout.minimumInteritemSpacing = 3;
    classLayout.minimumLineSpacing = 3;
    self.classifyCollectionView.delegate = self;
    self.classifyCollectionView.dataSource = self;
    [self.classifyCollectionView registerNib:[UINib nibWithNibName:@"ClassifyCollectionViewCell" bundle:nil] forCellWithReuseIdentifier:@"classify"];
    [self setClassData];

    // 修改popSoonCollection的layout值
    UICollectionViewFlowLayout *popLayout = (UICollectionViewFlowLayout *)self.popSoonCollectionView.collectionViewLayout; // 强转以匹配类型
    // 一行放三个collectionView
    self.popItemWidth = (KWIDTH - 8*5) / 3;
    // 设置item
    popLayout.itemSize = CGSizeMake(self.popItemWidth, self.popItemWidth*1.4);
    self.popSoonCollectionView.delegate = self;
    self.popSoonCollectionView.dataSource = self;
    [self.popSoonCollectionView registerNib:[UINib nibWithNibName:@"PopSoonCollectionViewCell" bundle:nil] forCellWithReuseIdentifier:@"popSoon"];
    [self hotMovieDataRequest];
    self.playingPage = 1;
    self.soonPage = 1;
    self.popSoonCollectionView.alwaysBounceVertical = YES;
    self.popSoonCollectionView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [self refreshPopCollectionViewDataWithIndex:self.segmentController.selectedSegmentIndex];
    }];
    
}
# pragma mark --- 设置classify界面 ---
- (void)setClassData{
    NSArray *titleArray = @[@"剧情",@"爱情",@"喜剧",@"动作",@"动画",@"记录",@"科幻",@"古装",@"悬疑",@"惊悚"];
    NSArray *idArray = @[@80,@92,@77,@81,@91,@105,@82,@79,@99,@83];
    self.classifyArray = [NSMutableArray array];
    for (int i = 0; i < 10; i++) {
        MovieLibraryMainModel *classifyModel = [[MovieLibraryMainModel alloc]init];
        [classifyModel setValue:titleArray[i] forKey:@"Title"];
        [classifyModel setValue:idArray[i] forKey:@"Id"];
        [self.classifyArray addObject:classifyModel];
    }
    dispatch_async(dispatch_get_main_queue(),^{
        [self.classifyCollectionView reloadData];
    });
}
# pragma mark --- 热门电影数据请求 ---
- (void)hotMovieDataRequest
{
    [RequestManager requestWithUrl:@"http://static.v6v7.com/pingping_japi/movie/findhot" requestType:RequestTypeGET parDic:nil finshed:^(NSData *data) {
        NSDictionary *originalDic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        NSMutableArray *resultArray = originalDic[@"result"];
        self.popSoonArray = [NSMutableArray array];
        for (NSMutableDictionary *resultDic in resultArray) {
            HotModel *hotModel = [[HotModel alloc]init];
            [hotModel setValuesForKeysWithDictionary:resultDic];
            [self.popSoonArray addObject:hotModel];
        }
        // 主线程
        dispatch_async(dispatch_get_main_queue(),^{
            [self.popSoonCollectionView reloadData];
        });
    } error:^(NSError *error) {
        NSLog(@"热门电影请求数据错误");
    }];

}

# pragma mark --- 正在热映和即将上映数据请求 ---
- (void)playingAndSoonMovieDataRequestWithUrl:(NSString *)url{
    // page = 1 控制页数  page_size=12 控制请求的数量
    [RequestManager requestWithUrl:url requestType:RequestTypeGET parDic:nil finshed:^(NSData *data) {
        NSDictionary *originalDic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        NSMutableDictionary *resultDic = originalDic[@"result"];
        // 记录 数据总个数
        self.soonTotalCount = [resultDic[@"count"] integerValue];
        NSMutableArray *dataArray = resultDic[@"data"];
        self.popSoonArray = [NSMutableArray array];
        for (NSMutableDictionary *dataDic in dataArray) {
            SoonModel *soonModel = [[SoonModel alloc]init];
            [soonModel setValuesForKeysWithDictionary:dataDic];
            [self.popSoonArray addObject:soonModel];
        }
        if (self.popSoonArray.count == self.soonTotalCount) {
            dispatch_async(dispatch_get_main_queue(), ^{
                UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"没有更多数据了" preferredStyle:UIAlertControllerStyleAlert];
                UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleCancel handler:nil];
                [alert addAction:cancelAction];
                [self presentViewController:alert animated:YES completion:nil];
            });
        }
        // 主线程
        dispatch_async(dispatch_get_main_queue(),^{
            [self.popSoonCollectionView reloadData];
        });
    } error:^(NSError *error) {
        NSLog(@"即将上映请求数据错误");
    }];

}
# pragma mark --- 分栏下表改变事件 ---
- (void)segmentAction:(UISegmentedControl *)segment
{
    if (segment.selectedSegmentIndex == 0) {
        [self hotMovieDataRequest];
    }
    else if (segment.selectedSegmentIndex == 1){
        [self playingAndSoonMovieDataRequestWithUrl:@"http://static.v6v7.com/snowman_api/movie_traces/movie_playing_list?page=1&page_size=12"];
    }
    else
    {
        // page = 1 控制页数  page_size=12 固定数量
        [self playingAndSoonMovieDataRequestWithUrl:@"http://static.v6v7.com/snowman_api/movie_traces/movie_later_list?page=1&page_size=12"];
    }
}
# pragma mark --- popCollectionView的下拉刷新 ---
- (void)refreshPopCollectionViewDataWithIndex:(NSInteger)segmentIndex
{
    if (segmentIndex == 0) {
        [self hotMovieDataRequest];
    }
    else if (segmentIndex == 1){
        self.playingPage++;
        [self playingAndSoonMovieDataRequestWithUrl:[NSString stringWithFormat:@"http://static.v6v7.com/snowman_api/movie_traces/movie_playing_list?page=%ld&page_size=12", _playingPage]];
    }
    else{
        self.soonPage++;
        [self playingAndSoonMovieDataRequestWithUrl:[NSString stringWithFormat:@"http://static.v6v7.com/snowman_api/movie_traces/movie_later_list?page=%ld&page_size=12", _soonPage]];
    }
    dispatch_async(dispatch_get_main_queue(), ^{
        [self.popSoonCollectionView.mj_header endRefreshing];
    });
}
# pragma mark --- collectionView的代理方法如下 ---
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return 1;
}
# pragma mark --- 返回分区item个数 ---
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    if ([collectionView isEqual:self.classifyCollectionView]) {
        return self.classifyArray.count;
    }
    else{
        return self.popSoonArray.count;
    }
}
# pragma mark --- 返回item ---
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    if ([collectionView isEqual:self.classifyCollectionView]) {
        ClassifyCollectionViewCell *item = [collectionView dequeueReusableCellWithReuseIdentifier:@"classify" forIndexPath:indexPath];
        MovieLibraryMainModel *classifyModel = self.classifyArray[indexPath.row];
        item.pictureView.image = [UIImage imageNamed:classifyModel.Title];
        item.classTitle.text = [NSString stringWithFormat:@"# %@", classifyModel.Title];
        return item;
    }
    else{
        PopSoonCollectionViewCell *item = [collectionView dequeueReusableCellWithReuseIdentifier:@"popSoon" forIndexPath:indexPath];
        if (self.segmentController.selectedSegmentIndex == 0) {
            HotModel *model = self.popSoonArray[indexPath.row];
            [item.pictureView sd_setImageWithURL:[NSURL URLWithString:model.poster]];
            item.movieTitle.text = model.title;
        }
        else{
            SoonModel *model = self.popSoonArray[indexPath.row];
            [item.pictureView sd_setImageWithURL:[NSURL URLWithString:model.poster]];
            item.movieTitle.text =  model.title;
        }
        return item;
    }
}

# pragma mark --- 点击item ---
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    if (collectionView == self.classifyCollectionView) {
        FiltrateViewController *filtrateDetailVc = [[FiltrateViewController alloc]initWithNibName:@"FiltrateViewController" bundle:nil];
        MovieLibraryMainModel *mainModel = self.classifyArray[indexPath.row];
        filtrateDetailVc.classifyId = mainModel.Id;
        filtrateDetailVc.classifyTitle = mainModel.Title;
        filtrateDetailVc.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:filtrateDetailVc animated:YES];
    }
    else{
        LibraryDetailViewController *libraryDetailVc = [[LibraryDetailViewController alloc]initWithNibName:@"LibraryDetailViewController" bundle:nil];
        if (self.segmentController.selectedSegmentIndex == 0) {
            HotModel *hotModel = self.popSoonArray[indexPath.row];
            libraryDetailVc.movieId = [hotModel.Id stringValue];
        }
        else{
            SoonModel *soonModel = self.popSoonArray[indexPath.row];
            libraryDetailVc.movieId = soonModel.Id;
        }
        libraryDetailVc.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:libraryDetailVc animated:YES];
    }
    
}
# pragma mark --- 返回集合视图整体的上、左、下、右 ---
- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
    if ([collectionView isEqual:self.classifyCollectionView]) {
        return UIEdgeInsetsMake(0, 0, 0, 0);
    }
    else{
        return UIEdgeInsetsMake(0, 8, 5, 8);
    }
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
